package net.zoneland.zrdp.quartz.util;

import java.time.Duration;
import java.time.LocalDateTime;

import net.zoneland.zrdp.quartz.mapstruct.SysJobConverter;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.zoneland.zrdp.common.constant.Constants;
import net.zoneland.zrdp.common.constant.ScheduleConstants;
import net.zoneland.zrdp.common.utils.StringUtilPlus;
import net.zoneland.zrdp.common.utils.spring.SpringUtils;
import net.zoneland.zrdp.quartz.domain.SysJob;
import net.zoneland.zrdp.quartz.domain.SysJobLog;
import net.zoneland.zrdp.quartz.service.ISysJobLogService;

/**
 * 抽象quartz调用
 *
 * @author zonevue
 */
public abstract class AbstractQuartzJob implements Job {
    private static final Logger LOGGER = LoggerFactory.getLogger(AbstractQuartzJob.class);

    /**
     * 线程本地变量
     */
    private static final ThreadLocal<LocalDateTime> threadLocal = new ThreadLocal<>();

    @Override
    public void execute(final JobExecutionContext context) {
        final Object jobData = context.getMergedJobDataMap().get(ScheduleConstants.TASK_PROPERTIES);
        if (jobData instanceof SysJob) {
            // MapStruct copy 对象。
            final SysJob sysJob = SysJobConverter.INSTANCE.sysJobCopy((SysJob)jobData);
            try {
                before();
                doExecute(context, sysJob);
                after(sysJob, null);
            } catch (final Exception e) {
                LOGGER.error("任务执行异常  - ：", e);
                after(sysJob, e);
            }
        }
    }

    /**
     * 执行前
     *
     */
    protected void before() {
        threadLocal.set(LocalDateTime.now());
    }

    /**
     * 执行后
     *
     * @param sysJob 系统计划任务
     * @param e 异常信息
     */
    protected void after(final SysJob sysJob, final Exception e) {
        final LocalDateTime startTime = threadLocal.get();
        threadLocal.remove();

        final SysJobLog sysJobLog = new SysJobLog();
        sysJobLog.setJobName(sysJob.getJobName());
        sysJobLog.setJobGroup(sysJob.getJobGroup());
        sysJobLog.setInvokeTarget(sysJob.getInvokeTarget());
        sysJobLog.setStartTime(startTime);
        final LocalDateTime stopTime = LocalDateTime.now();
        sysJobLog.setStopTime(stopTime);

        // 使用 Duration.between 计算两个 LocalDateTime 之间的持续时间
        final long runMs = Duration.between(startTime, stopTime).toMillis();
        sysJobLog.setJobMessage(sysJobLog.getJobName() + " 总共耗时：" + runMs + "毫秒");
        if (e != null) {
            sysJobLog.setStatus(Constants.FAIL);
            final String errorMsg = StringUtilPlus.truncateToValidLengthForMysql(ExceptionUtils.getStackTrace(e));
            sysJobLog.setExceptionInfo(errorMsg);
        } else {
            sysJobLog.setStatus(Constants.SUCCESS);
        }

        // 写入数据库当中
        SpringUtils.getBean(ISysJobLogService.class).addJobLog(sysJobLog);
    }

    /**
     * 执行方法，由子类重载
     *
     * @param context 工作执行上下文对象
     * @param sysJob 系统计划任务
     * @throws Exception 执行过程中的异常
     */
    protected abstract void doExecute(JobExecutionContext context, SysJob sysJob) throws Exception;
}
